package net.chrisrichardson.ec2deployer.util

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory


public class SocketWaiter {

  Log logger = LogFactory.getLog(getClass())

  private String hostName
  private int port
  private int timeoutInSeconds
  
  SocketWaiter(String hostName, int port, int timeoutInSeconds) {
    this.hostName = hostName
    this.port = port
    this.timeoutInSeconds = timeoutInSeconds
  }


  void waitForSocket() {
    for (int i: 0..timeoutInSeconds) {
        if (isAvailable())
            break;
        Thread.sleep 1000
    }
  }

  boolean isAvailable() {
      Socket s = null
      try {
          s = new Socket();
          s.connect(new InetSocketAddress(hostName, port), 5 * 1000);
          logger.debug "Connected"
          return true;
      } catch (IOException e) {
          logger.debug("connection failed:", e)
          return false;
      } finally {
          try {
              if (s) s.close();
          } catch (IOException e) {
          }
      }
  }

}